import json
import re

def format_js_code(js_code):
    formatted_lines = []
    # 遍历每行代码
    for line in js_code.splitlines():
        # 去除行尾空格
        stripped_line = line.rstrip()
        # 如果当前行为空，直接将其添加到formatted_lines
        if not stripped_line:
            formatted_lines.append(line)
            continue

        # 获取最后一个字符
        last_char = stripped_line[-1]

        if last_char == '}':
            # 如果行以 } 结束，且下一行不是结束的配对括号，则追加逗号
            if '};' not in stripped_line and not any(map(stripped_line.endswith, [",{", "(,", "[,"])):
                line = line + ','
        elif last_char in ("'", '"') or last_char.isdigit() or stripped_line.endswith(('true', 'false')):
            # 如果行以引号、布尔值、数字结尾，则追加逗号
            line = line + ','

        # 如果行尾已经是逗号或行尾是 { 或 [ 则不处理
        formatted_lines.append(line)

    return '\n'.join(formatted_lines)




# 自定义函数用于处理布尔值转换
def bool_to_str(val):
    if isinstance(val, bool):
        return str(val).lower()  # 将布尔值转换为小写字符串
    raise TypeError("Object of type %s is not JSON serializable" % type(val))


# Custom JSON decoder to convert boolean strings to boolean values
def custom_json_decoder(data):
    for key, value in data.items():
        if value == 'true':
            data[key] = True
        elif value == 'false':
            data[key] = False
    return data


def generator_data(data_info):
    head_txt = "import { BasicColumn, FormSchema } from '/@/components/Table';\n"
    column_schemas = ''
    table_info = json.loads(data_info.table_info)
    column_info = table_info.get('searchInfo')
    for item in column_info:
        column_schema = f'''  {{
    title: '{item.get('column_name', '')}',
    dataIndex: '{item['field_name']}',
    width: '{item.get('width', '')}',
    fixed: '{item.get('freeze', '')}',
    align: '{item.get('align', '')}',
    auth: ['{data_info.code + ':' + item['field_name']}'],
    resizable: '{str(item.get('resizable', '')).lower()}',
  }},
'''
        column_schemas = column_schemas + column_schema
    column_txt = f'''
export const columns: BasicColumn[] = [\n{column_schemas}];
'''

    search_schemas = ''
    table_info = json.loads(data_info.table_info)
    search_info = table_info.get('searchInfo')
    for item in search_info:
        search_schema = f'''
  {{
    label: '{item['column_name']}',
    field: '{item['field_name']}',
    component: 'Input',
    colProps: {{ span: 6 }},
  }},
'''
        search_schemas = search_schemas + search_schema
    search_txt = f'''
export const searchFormSchema: FormSchema[] = [{search_schemas}];
'''
    form_info = json.loads(data_info.form_info).get('schemas')
    for item in form_info:
        item.pop('key')
        item.pop('icon')

    id_dict = {
        'field': 'id',
        'label': 'id',
        'component': 'Input',
        'show': False,
    }
    form_info.insert(0, id_dict)
    json_str = json.dumps(form_info, ensure_ascii=False, indent=2, default=bool_to_str)

    js_object = re.sub(r'"\b(\w+)\b":', r'\1:', json_str)
    form_schemas = js_object.replace('"', "'")
    form_txt = f'''
export const formSchema: FormSchema[] = {form_schemas};
'''

    form_txt = f"{format_js_code(form_txt)}\n"
    return head_txt + column_txt + search_txt + form_txt
